package com.siashan.toolkit.core.enums;

import com.siashan.toolkit.core.exception.EnumException;

import java.io.Serializable;

/**
 * 枚举工具类
 *
 * @author siashan
 * @since 1.0.1
 **/
public class EnumUtil {

    /**
     * 根据code得到对应的枚举值
     *
     * @param enumClass 枚举的class类
     * @param code      枚举的code值
     * @return 枚举
     * @since V1.0.1
     */
    public static <T extends IBaseEnum> T getEnum(Class<T> enumClass, Serializable code) {
        return getEnum(enumClass, code, null);
    }

    /**
     * 根据code得到对应的枚举值
     *
     * @param enumClass 枚举的class类
     * @param code      枚举的code值
     * @param withCheck 是否需要校验枚举
     * @return 枚举
     * @since V1.1.8
     */
    public static <T extends IBaseEnum> T getEnum(Class<T> enumClass, Serializable code, boolean withCheck) {
        T anEnum = getEnum(enumClass, code, null);
        if (withCheck) {
            if (null == anEnum) {
                throw new EnumException("参数非法！");
            }
        }
        return anEnum;
    }


    /**
     * 根据code得到对应的枚举值，如果不存在则返回默认值
     *
     * @param enumClass   枚举的class类
     * @param code        枚举的code值
     * @param defaultEnum 默认值
     * @return 枚举
     * @since V1.0.1
     */
    public static <T extends IBaseEnum> T getEnum(Class<T> enumClass, Serializable code, T defaultEnum) {
        for (T enumObj : enumClass.getEnumConstants()) {
            if (code.equals(enumObj.getCode())) {
                return enumObj;
            }
        }
        return defaultEnum;
    }


    /**
     * 校验枚举是否匹配
     *
     * @param enumz 枚举
     * @param code  枚举code
     * @return true/false
     */
    public static boolean equals(IBaseEnum enumz, Serializable code) {
        return enumz.getCode().equals(code);
    }


    public static void main(String[] args) {
        boolean equals = EnumUtil.equals(IntSwitch.YES, 1);
        System.out.println(equals);
    }

}
